package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.dto.SubmitDTO;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import com.itheima.health.vo.OrderMemberSetmealVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;


/**
 * 预约ServiceImpl
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 预约提交
     * @param submitDTO
     * @return
     */
    @Transactional
    @Override
    public Order submit(SubmitDTO submitDTO) throws ParseException {
//        将格式转换为Date
        if (submitDTO.getOrderDate()==null){
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }
        String orderDate = submitDTO.getOrderDate();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        Date subDate = ft.parse(orderDate);



        Order insertOrder = new Order();

//      转换为Integer
        Integer setmealId = Integer.valueOf(submitDTO.getSetmealId());

//        先查寻预约当天是否 约满
        OrderSetting orderSettingList = orderSettingDao.selectfull(subDate);
        int reservations = orderSettingList.getReservations();
//        查询是否有预约日期
        if (orderSettingList==null || orderSettingList.getNumber()<=reservations){
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }



//            再查询是否是会员
//        格式转换
        LocalDate now1 = LocalDate.now();

        Member member = memberDao.selectGetByIdCode(submitDTO.getTelephone());

        Member member1 = new Member();
        member1.setName(submitDTO.getName());
        member1.setSex(submitDTO.getSex());
        member1.setIdCard(submitDTO.getIdCard());
        member1.setName(submitDTO.getName());
        member1.setPhoneNumber(submitDTO.getTelephone());
        member1.setRegTime(now1);

//            不是会员
        if (member==null){
            memberDao.insertBySubmit(member1);
            insertOrder.setMemberId(member1.getId());
        }else {
            memberDao.update(member1);
            //            查询该会员是否在当天预约过其他项目
            Order order = orderDao.selectOrder(member.getId(),subDate);
            if (order!=null){
                throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
            }
            insertOrder.setMemberId(member.getId());
        }



//      验证码
        //从redis中获取到手机号对应的验证码和时间毫秒值
        String s = (String) redisTemplate.opsForValue().get(submitDTO.getTelephone());
        String[] timeAndCode = s.split("_");
        long start = Long.parseLong(timeAndCode[0]);
        String code = timeAndCode[1];
        //获取当前时间毫秒值
        long now2 = System.currentTimeMillis();

        //判断验证码过期时间
        long time = now2 - start;
        if (time>=120000){
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        }

        //判断填写的验证码是否与数据库中的验证码相同
        if (!submitDTO.getValidateCode().equals(code)){
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        }
        int resNew = reservations + 1;

        orderSettingDao.updateres(subDate,resNew);

//            新增预约订单


        insertOrder.setOrderDate(subDate);
        insertOrder.setOrderStatus(Order.ORDERSTATUS_NO);
        insertOrder.setOrderType(Order.ORDERTYPE_WEIXIN);
        insertOrder.setSetmealId(setmealId);


        orderDao.insert(insertOrder);



//            封装返回数据  orderDao.selectAll(insertOrder);


        return insertOrder;
    }


    @Override
    public OrderMemberSetmealVO findById(Integer id) {
        //new一个新的返回对象用于封装数据
        //去数据库表中查询数据
        OrderMemberSetmealVO orderMemberSetmealVO = orderDao.select(id);

        return orderMemberSetmealVO;
    }
}
